import {
  Injectable,
  CanActivate,
  ExecutionContext,
  ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY, Role } from './../decorations/Role';
import { CreateUserDto } from 'src/server/user/dto/create-user.dto';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
  ) { }

  canActivate(context: ExecutionContext): boolean {
    try {
      const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
        context.getHandler(),
        context.getClass(),
      ]);
      // 无需权限
      if (!requiredRoles) {
        return true;
      }
      // 获取 挂载的登陆信息
      const { userinfo } = context.switchToHttp().getRequest();
      // 是否有权限
      const result = requiredRoles.some(
        (role) => (userinfo as CreateUserDto).role?.includes(role),
      );
      // 有权限
      if (result) {
        return true;
      }
    } catch (e) {
      throw new ForbiddenException('', '抱歉！您暂无权限访问~');
    }
  }
}
